﻿using Autofac;
using FluentValidation;
using FluentValidation.Results;
using Lamp.Core.Common.TypeConverter;
using Lamp.Core.Protocol.Communication;
using Lamp.Core.Protocol.Server;
using Lamp.Core.Server;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;

namespace Lamp.Validation
{
    public class ValidMiddleware
    {
        private readonly IContainer _container;
        private readonly RequestDel _next;

        public ValidMiddleware(RequestDel next, IContainer container)
        {
            _container = container;
            _next = next;
        }

        public Task Invoke(RemoteExecutorContext context)
        {
            IValidatorFactory factory = _container.Resolve<IValidatorFactory>();

            foreach (ParameterInfo p in context.ServiceEntry.Parameters)
            {
                Type type = p.ParameterType;

                if (type.IsClass && !type.FullName.StartsWith("System.") && typeof(List<ServerFile>) != type)
                {
                    IValidator validator = factory.GetValidator(type);
                    if (validator != null)
                    {
                        context.RemoteInvokeMessage.Parameters.TryGetValue(p.Name.ToLower(), out object value);
                        if (value != null)
                        {
                            object parameter = _container.Resolve<ITypeConvertProvider>().Convert(value, type);
                            ValidationResult result = validator.Validate(parameter);
                            if (!result.IsValid)
                            {
                                ValidationFailure error = result.Errors.First();
                                return context.Response.WriteAsync(context.TransportMessage.Id, new RemoteCallBackData
                                {
                                    ErrorMsg = $"字段{error.PropertyName}验证错误，错误信息为：{error.ErrorMessage}",
                                    ErrorCode = "400"
                                });
                            }
                        }
                    }
                }
            }
            return _next.Invoke(context);
        }
    }
}
